package com.youxin.dataStream.custormSink;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.redis.RedisSink;
import org.apache.flink.streaming.connectors.redis.common.config.FlinkJedisPoolConfig;
import org.apache.flink.streaming.connectors.redis.common.mapper.RedisCommand;
import org.apache.flink.streaming.connectors.redis.common.mapper.RedisCommandDescription;
import org.apache.flink.streaming.connectors.redis.common.mapper.RedisMapper;
import org.apache.flink.util.Collector;

import java.util.ArrayList;
import java.util.List;

/**
 *(a,1) (a,1)(b,1)(b,1)
 * keyby  
 *(a,1) (a,1)      (b,1)(b,1)
 *
 * reduce
 *
 *
 */
public class StreamRedisSink {
    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        List<String> list = new ArrayList<>();
        list.add("hello");
        DataStreamSource<String> lines = env.fromCollection(list);
        SingleOutputStreamOperator<Tuple2<String, Long>> wordAndOne = lines.flatMap(new FlatMapFunction<String, Tuple2<String, Long>>() {
            @Override
            public void flatMap(String s, Collector<Tuple2<String, Long>> collector) throws Exception {
                String[] s1 = s.split(" ");
                for (String word : s1) {
                    collector.collect(new Tuple2<String, Long>(word, 1L));
                }
            }
        });

        FlinkJedisPoolConfig conf = new FlinkJedisPoolConfig.Builder().setHost("redisHost").setPort(6379).build();
        RedisSink<Tuple2<String,Long>> redisSink = new RedisSink<>(conf,new MyRedisMapper());
        wordAndOne.addSink(redisSink);
        try {
            env.execute("StreamToRedis");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public  static class MyRedisMapper implements RedisMapper<Tuple2<String,Long>>{
        @Override
        public RedisCommandDescription getCommandDescription() {
            // 设置hash的时候并且制定hash的key
            //return new RedisCommandDescription(RedisCommand.HSET,"flink");
            // String 类型的
            return new RedisCommandDescription(RedisCommand.SET);
        }

        @Override
        public String getKeyFromData(Tuple2<String, Long> stringLongTuple2) {
            // key的组装
            return stringLongTuple2.f0;
        }

        @Override
        public String getValueFromData(Tuple2<String, Long> stringLongTuple2) {
            // value的组装
            return stringLongTuple2.f1+"";
        }
    }
}
